<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace  app\cardeadmin\controller;

use app\api\controller\Index as apiIndex;
use app\common\controller\AdminController;
use app\common\model\FundCheck;
use app\common\model\ManageCard;
use app\common\model\User as UserModel;
use app\common\model\UserCheck;
use app\common\model\UserChild;
use app\common\model\ManageLog;
use app\common\model\UserSet;
use think\facade\Db;
use think\facade\View;

/**
 * 会员管理
 * Class User
 * @package app\admin\controller
 */
class User extends  AdminController {

    /**
     * 用户列表
     * @author 救火队队长
     */
    public function  index() {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function  indexBold() {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminBold(input('param.'));
        }
        return View::fetch();
    }

    public function userAdd()
    {
        if($this->request->isPost()) {
            //header("HTTP/1.1 402"); exit;
            $data = input('param.');
            $user       = $data['name'];
            $password   = $data['password'];
            $user_list  = Db::name('user')->where(['username'=>$user])->find();
            if(!empty($user_list)){
                return $this->err('用户已存在.');
            }
            $create_time=getUtcTime();

            $default_user_list = Db::name('user')->where(['id'=>1])->find();
            $usa_rate          = $default_user_list['usa_rate'];
            $dec_rate          = $default_user_list['dec_rate'];

            $re         = Db::name('user')->save([
                'username'  => $user,
                'password'  => md5(md5($password) . $create_time),
                'user_num'  => getRandNumber(),
                'usa_rate'  => $usa_rate,
                'dec_rate'  => $dec_rate,
                'ctime'     => $create_time
            ]);

            if($re){
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        return View::fetch();
    }

    /**
     * 美元汇率全局更新
     * @return string|\think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function userRate()
    {
        $rate = Db::name('user')->where(['id'=>1])->value('usa_rate');
        if($this->request->isPost()) {

            $data = input('param.');
            $new_rate   = $data['new_rate'];
            if($rate - $new_rate == 0){
                return $this->err('填写的比例和默认比例一致，请重新提交.');
            }
            $re  = Db::name('user')
                ->where("usa_rate = {$rate}")
                ->update(['usa_rate' => $new_rate]);

            if($re){
                Db::name('manage_log')->save([
                    'manage_id' => $this->manage_id,
                    'desc'      => '(All)up user usa rate',
                    'content'   => json_encode(['old_rate'=>$rate , 'new_rate'=>$new_rate]),
                    'ip'        => ip(),
                    'ctime'     => getUtcTime()
                ]);
                return $this->scs('update success');
            }else{
                return $this->err('update error');
            }
        }
        View::assign([
            'currey_rate'              => $rate,
        ]);
        return View::fetch();
    }

    /**
     * 拒付比例全局更新
     * @return string|\think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function userDecRate()
    {
        $rate = Db::name('user')->where(['id'=>1])->value('dec_rate');
        if($this->request->isPost()) {

            $data = input('param.');
            $new_rate   = $data['new_rate'];
            if($rate - $new_rate == 0){
                return $this->err('填写的比例和默认比例一致，请重新提交.');
            }
            $re  = Db::name('user')
                ->where("dec_rate = {$rate}")
                ->update(['dec_rate' => $new_rate]);

            if($re){
                Db::name('manage_log')->save([
                    'manage_id' => $this->manage_id,
                    'desc'      => '(All)up user dec rate',
                    'content'   => json_encode(['old_rate'=>$rate , 'new_rate'=>$new_rate]),
                    'ip'        => ip(),
                    'ctime'     => getUtcTime()
                ]);
                return $this->scs('update success');
            }else{
                return $this->err('update error');
            }
        }
        View::assign([
            'currey_rate'              => $rate,
        ]);
        return View::fetch();
    }

    public function  rateList() {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminRate(input('param.'));
        }
        return View::fetch();
    }

    public function indexData()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminTwo(input('param.'));
        }
        $list = Db::name('user_data')->where('user_id=2')->field('ctime')->find();

        $time = isset($list['ctime']) ? date('Y-m-d H:i:s',$list['ctime'] + 8*60*60) : '--';
        View::assign([
            'time'              => $time,
            'available_balance' => ''
        ]);
        return View::fetch();
    }

    public function indexData2()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminThree(input('param.'));
        }
        return View::fetch();
    }



    public function indexDataOther()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminOther(input('param.'));
        }
        View::assign([
            'time'              => getUtcTime(false),
        ]);
        return View::fetch();
    }

    public function indexDataHistory()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataHistory(input('param.'));
        }
        return View::fetch();
    }

    public function userDataUp()
    {
        $userModel = new UserModel();
        $result    = $userModel->updataUserData();

        if($result['blog']){
//            $total_deposit  = $result['total_deposit'];
//            $sum_amount     = $result['sum_amount'];
//            $diff_amount    = $result['diff_amount'];
            return $this->scs('Confirm the successful.' , '' ,
                [
                    'time'              => $result['time'],
//                    'tran_amount'       => $result['tran_amount'],
//                    'available_balance' => $result['available_balance'],
//                    'sum_amount'        => $sum_amount,
//                    'total_deposit'     => $total_deposit,
//                    'diff_amount'       => $diff_amount
                ]);
        }else{
            return $this->scs('Confirm the failed.');
        }
    }

    public function userAvailableBalance()
    {
        $api_balance = apiIndex::searchOtherAdmin([
            'method'        => 'GET',
            'add_url'       => '/programreserve/balances',
            'request_data'  => ''
        ]);
        $api_blog = $api_balance['blog'];
        if($api_blog){
            $response           = json_decode($api_balance['response'] , true);
            $available_balance  = $response['available_balance'] ?? 0.00;
            return $this->scs('Confirm the successful.' , '' ,
                [
                    'time'              => getUtcTime(false),
                    'available_balance' => $available_balance,
                ]);
        }else{
            return $this->scs('Confirm the failed.');
        }
    }

    public function changeToken()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $business_token = trim($data['business_token']);
            $user_token_list      = Db::name('user_check')->where([
                'business_token' => $business_token,
                'check_result'   => 1
            ])->find();
            if(!$user_token_list) return $this->err("The Business Token does not exist.");

            $userMoney  = new UserModel();
            $data       += ['manage_id' => $this->manage_id];
            $data       += ['parent_id' => $user_token_list['id']];
            $re         = $userMoney->changeToken($data);
            if($re){
                return $this->scs('Change Token successful.');
            }else{
                return $this->scs('Change Token Error');
            }
        }
        $check_id = input('get.check_id');
        View::assign([
            'check_id'   => $check_id
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function setKey()
    {
        $user_id = input('post.id');
        $key     = randomSecretkeys(32);
        $re      = Db::name('user')->where(['id'=>$user_id])->update(['secret_key'=>$key]);
        if($re){
            return $this->scs('Confirm the successful.');
        }else{
            return $this->scs('Confirm the failed.');
        }
    }

    public function userKey()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserModel();
            return $userModel->tableDataAdminThree(input('param.'));
        }
        return View::fetch();
    }

    public function editUserName()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $new_name   = trim($data['new_name']);
            if(!check_param($new_name , 'email')) return $this->err("Username is not a mailbox.");
            $user_list      = Db::name('user')->where(['username' => $new_name])->find();
            if($user_list) return $this->err("Username(User) already exists.");
            $user_check_list      = Db::name('user_check')->where(['username' => $new_name])->find();
            if($user_check_list) return $this->err("Username(UserCheck) already exists.");

            $userMoney  = new UserModel();
            $data += ['manage_id' => $this->manage_id];
            $re = $userMoney->changeUserName($data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $user_list = Db::name('user')->find($user_id);
        $current_username = $user_list['username'];
        //当月的起始时间和结束时间
        View::assign([
            'current_username'  => $current_username,
            'user_id'           => $user_id,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function  userChild() {
        if($this->request->isAjax())
        {
            $userModel = new UserChild();
            return $userModel->tableDataAdmin(input('param.'));
        }
        $user_id = input('get.user_id');
        View::assign([
            'user_id'   => $user_id
        ]);
        return View::fetch();
    }
    
    public function childUser()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserChild();
            return $userModel->tableDataChild(input('param.'));
        }
        return View::fetch();
    }

    public function editStatus()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $status_num  = $data['status_num'];
            $user_id    = $data['user_id'];
            $manage_id  = $this->manage_id;

            $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
            $status      = $user_list['status'];
            $user_name  = $user_list['username'];

            if($status == $status_num) return $this->err('请更改用户状态后更新.');

            $re         = Db::name('user')->where(['id'=>$user_id])
                ->update(['status'=>$status_num]);

            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'update user status',
                'content'   => [
                    'username' => $user_name,
                    'old_status' => $status ,
                    'new_status' => $status_num]
            ]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'status_num'     => $user_info['status']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function oldCheckRef()
    {
        $user_id = input('post.id');

        $user_list = Db::name('user')->where(['id'=>$user_id])->find($user_id);
        $grade     = $user_list['grade'];
        $grade_new = $user_list['grade_new'];
        if($grade == 1 && $grade_new == 0){
            $re = Db::name('user')->where(['id'=>$user_id])
                ->update([
                    'name'      =>'',
                    'id_card'   =>'',
                    'grade'     => 0
                ]);
            if($re){
                return $this->scs('更新成功.');
            }else{
                return $this->err('更新失败，请联系管理员.');
            }
        }else{
            return $this->err('更新失败，请联系管理员.');
        }
    }

    public function isCheck()
    {
        $user_id = input('post.id');
        $userMoney  = new UserModel();
        $re = $userMoney->isCheck([
            'user_id'   => $user_id ,
            'manage_id' => $this->manage_id
        ]);
        if($re){
            return $this->scs('Edit the successful.');
        }else{
            return $this->scs('Edit the failed.');
        }
    }

    public function isCode()
    {
        $user_id = input('post.id');
        $userMoney  = new UserModel();
        $re = $userMoney->isCode([
            'user_id'   => $user_id ,
            'manage_id' => $this->manage_id
        ]);
        if($re){
            return $this->scs('Edit the successful.');
        }else{
            return $this->scs('Edit the failed.');
        }
    }


    public function editDataShow()
    {
        $user_id = input('post.id');
        $userMoney  = new UserModel();
        $re = $userMoney->editDataShow([
            'user_id'   => $user_id ,
            'manage_id' => $this->manage_id
        ]);
        if($re){
            return $this->scs('Edit the successful.');
        }else{
            return $this->scs('Edit the failed.');
        }
    }


    public function editRz()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $rz_status  = $data['rz_status'];
            $rz_status_two  = $data['rz_status_two'];
            $user_id    = $data['user_id'];
            $manage_id  = $this->manage_id;

            $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
            $grade      = $user_list['grade'];
            $grade_new = $user_list['grade_new'];
            $user_name  = $user_list['username'];

            if($grade == $rz_status && $rz_status_two == $grade_new) return $this->err('请更改用户状态后更新.');

            $re         = Db::name('user')->where(['id'=>$user_id])
                ->update([
                    'grade'=>$rz_status,
                    'grade_new'=>$rz_status_two
                ]);

            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'update user check',
                'content'   => [
                    'username' => $user_name,
                    'old_grade' => $grade ,
                    'new_grade' => $rz_status,
                    'old_grade2' => $grade_new ,
                    'new_grade2' => $rz_status_two
                ]
            ]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'           => $user_id,
            'rz_status'         => $user_info['grade'],
            'rz_status_two'     => $user_info['grade_new']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editMoney()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = $data['money'];
            $user_id    = $data['user_id'];
            $up_status  = $data['up_status'];
            $manage_id  = $this->manage_id;
            if($up_status == 1){
                if(!check_param($money , 'zfInt')) return $this->err("It must be a positive integer.");
            }
            if($money == 0) return $this->err("Amount cannot be equal to 0.");
            $userMoney  = new UserModel();
            $user_list  = $userMoney::find($user_id);
            $current_balance = $user_list['balance'];
            $user_name       = $user_list['username'];
            if($up_status == 1){
                if($money < 0){
                    if(($current_balance - abs($money)) <0){
                        return $this->err("Insufficient account balance.");
                    }
                }
            }
            $manage_balance = Db::name('manage')->where(['id'=> $manage_id])->value('balance');
            if($manage_balance - $money <0){
                return $this->err("管理员充值余额不足.");
            }
            $data += ['manage_id' => $manage_id ,
                        'balance' => $current_balance ,
                        'username'=> $user_name ];
            $re = $userMoney->changeBalance($data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'username'   => $user_info['username'],
            'money'     => $user_info['balance']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editRate()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = trim($data['money']);
            $user_id    = $data['user_id'];

            $user_list = Db::name('user')->where(['id'=> $user_id])->find();
            $username  = $user_list['username'];
            $usa_rate  = $user_list['usa_rate'];

            if($money < 0){
                return $this->err('汇率不能为负数.');
            }
            if($money > 10){
                return $this->err('汇率不能大于10.');
            }
            if($usa_rate - $money == 0){
                return $this->err('请变更不同汇率后再提交.');
            }

            $result = Db::name('user')->where(['id'=> $user_id])
                    ->update([
                        'usa_rate' => $money
                    ]);
            if($result){
                Db::name('manage_log')->save([
                    'manage_id' => $this->manage_id,
                    'desc'      => 'up user usa rate',
                    'content'   => json_encode(['username'=>$username , 'old_rate'=>$usa_rate , 'new_rate'=>$money]),
                    'ip'        => ip(),
                    'ctime'     => getUtcTime()
                ]);
                return $this->scs('Confirm the successful.');
            }else{
                return $this->err('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'username'   => $user_info['username'],
            'money'     => $user_info['usa_rate']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function editDecRate()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = trim($data['money']);
            $user_id    = $data['user_id'];

            $user_list = Db::name('user')->where(['id'=> $user_id])->find();
            $username  = $user_list['username'];
            $dec_rate  = $user_list['dec_rate'];

            if($money < 0){
                return $this->err('汇率不能为负数.');
            }
            if($money > 10){
                return $this->err('汇率不能大于10.');
            }
            if($dec_rate - $money == 0){
                return $this->err('请变更不同拒付比例后再提交.');
            }

            $result = Db::name('user')->where(['id'=> $user_id])
                ->update([
                    'dec_rate' => $money
                ]);
            if($result){
                Db::name('manage_log')->save([
                    'manage_id' => $this->manage_id,
                    'desc'      => 'up user dec rate',
                    'content'   => json_encode(['username'=>$username , 'old_rate'=>$dec_rate , 'new_rate'=>$money]),
                    'ip'        => ip(),
                    'ctime'     => getUtcTime()
                ]);
                return $this->scs('Confirm the successful.');
            }else{
                return $this->err('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'username'   => $user_info['username'],
            'money'     => $user_info['dec_rate']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editAmount()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = $data['money'];
            if(!check_param($money , 'zInt')) return $this->err("It must be a positive integer.");
            if($money < 1) return $this->err("The opening amount must be greater than $1.00.");
            $userMoney  = new UserModel();
            $data += ['manage_id' => $this->manage_id];
            $re = $userMoney->changeAmount($data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'money'     => $user_info['create_amount']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editOpen()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = $data['open_money'];
            if(!check_param($money , 'zInt')) return $this->err("It must be a positive integer.");
            if($money < 1) return $this->err("The opening amount must be greater than 1.");
            $userMoney  = new UserModel();
            $data += ['manage_id' => $this->manage_id];
            $re = $userMoney->changeOpen($data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id = input('get.user_id');
        $userModel = new UserModel();
        $user_info = $userModel->where(['id' => $user_id])->find();
        View::assign([
            'user_id'   => $user_id,
            'open_money'     => $user_info['open_amount']
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editMax()
    {
        if ($this->request->isAjax()) {
            $request  = input('param.');
            $logModel = new UserSet();
            $result   = $logModel::changeCardSet($request + ['manage_id' => $this->manage_id ]);
            if($result){
                return $this->scs('更新成功.');
            }else{
                return $this->scs('更新失败.');
            }
        }
        $user_id     = input('get.user_id');
        $list    = Db::name('user_set')->where(['user_id' => $user_id])->find();
        $set_id  = 0;
        if(empty($list)){
            $list   = Db::name('user_set')->where(['id' => 1])->find();
        }else{
            $set_id = $list['id'];
        }
        $card_set = json_decode($list['card_set'] , true);
        View::assign([
            'user_id'           => $user_id,
            'list'              => $card_set,
            'set_id'            => $set_id,
            'max_card'          => $list['max_card'],
            'zero_auth'         => $list['zero_auth'],
            'facebook'          => $list['facebook'],
            'declined'          => $list['declined'],
        ]);
        return  View::fetch();
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editPwd()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            if(!check_param($data['pwd'],'password')) return $this->err("The password must contain uppercase and lowercase letters, digits, special characters, and 12 to 32 bytes.");
            $userMoney  = new UserModel();
            $data       += ['manage_id' => $this->manage_id];
            $re         = $userMoney->changePwd($data);
            if($re['blog']){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs($re['msg']);
            }
        }
        $user_id = input('get.user_id');
        View::assign([
            'user_id'   => $user_id
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function editDesc()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $remark      = trim($data['remark']);
            if(empty($remark)) return $this->err("Please input Remark.");
            $re         = Db::name('user')->where(['id'=>$data['user_id']])
                ->update(['desc' => $remark]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $user_id    = input('get.user_id');
        $user_desc  = Db::name('user')->where(['id' => $user_id])->value('desc');
        View::assign([
            'user_id'   => $user_id,
            'desc'      => $user_desc
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function check()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $model = new UserCheck();
            return $model->tableData($data);
        }
        return View::fetch();
    }

    public function editCheck()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $model = new UserCheck();
            return $model->tableData($data);
        }
        $id = input('get.id');
        View::assign([
            'check_id'   => $id
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function checkSent()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $money      = $data['money'];
            $user_id    = $data['user_id'];
            if(!is_numeric($money)) return $this->err("Amount must be a number.");
            if($money == 0) return $this->err("Amount cannot be equal to 0.");
            $userMoney  = new UserModel();
            $user_list  = $userMoney::find($user_id);
            $current_balance = abs($user_list['balance']);
            $user_name       = $user_list['username'];
            if($money < 0){
                if(($current_balance - abs($money)) <0){
                    return $this->err("Insufficient account balance.");
                }
            }
            $data += ['manage_id' => $this->manage_id ,
                'balance' => $current_balance ,
                'username'=> $user_name ];
            $re = $userMoney->changeBalance($data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }
        $check_id = input('get.check_id');
        View::assign([
            'response'   => $this->getCheckInfo($check_id),
            "check_id"   => $check_id,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }
    public function getCheckInfo($check_id)
    {
        $list           = Db::name("user_check")->find($check_id);
        $applicant      = json_decode($list["applicant"] , true);
        $business_one   = json_decode($list["business_one"] , true);
        $business_two   = json_decode($list["business_two"] , true);
        $owner          = json_decode($list["owner"] , true);

        return [
            "business_name_legal"   => $business_one["business_name"],
            "business_name_dba"     => $business_one["fictitious_name"],
            "office_location"       => [
                "address1"      => $business_two['business_address'] . " " . $business_two['business_apartment'],
                "city"          => $business_two['business_city'],
                "state"         => $business_two['business_state'],
                "postal_code"   => $business_two['business_zip'],
            ],
            "phone"                 => $applicant["company_phone"],
            "date_established"      => $business_one["established_date"],
            "incorporation"         => [
                "is_public"             =>false,
                "incorporation_type"    => $business_two['incorporation_type'],
                "state_of_incorporation"=> $business_one['incorporation_state'],
                "name_registered_under" => $business_one["business_name"],
                "address_registered_under" => [
                    "address1"      => $business_two['business_address'] . " " . $business_two['business_apartment'],
                    "city"          => $business_two['business_city'],
                    "state"         => $business_two['business_state'],
                    "postal_code"   => $business_two['business_zip'],
                ]
            ],
            "taxpayer_id"           => $business_two['federal_tax_id'],
            "proprietor_or_officer" =>[
                "first_name"    => $owner['owner_first_name'],
                "last_name"     => $owner['owner_last_name'],
                "title"         => $owner['owner_job_title'],
                "home"          => [
                    "address1"  => $owner['owner_address'] . " " . $owner['owner_apartment'],
                    "city"      => $owner['owner_city'],
                    "state"     => $owner['owner_status'],
                    "postal_code"=> $owner['owner_zip']
                ],
                "dob"   => $owner['owner_date'],
                "phone" => $owner['owner_phone'],
                "email" => $applicant['email'],
            ],
            "beneficial_owner1" =>[
                "first_name"    => ($owner['owner_type'] != 1) ? $owner['owner_first_name2'] : $owner['owner_first_name'],
                "last_name"     => ($owner['owner_type'] != 1) ? $owner['owner_last_name2'] : $owner['owner_last_name'],
                "title"         => ($owner['owner_type'] != 1) ? $owner['owner_job_title2'] : $owner['owner_job_title'],
                "home"          => [
                    "address1"  => ($owner['owner_type'] != 1) ? ($owner['owner_address2'] . " " . $owner['owner_apartment2']): ($owner['owner_address'] . " " . $owner['owner_apartment']),
                    "city"      => ($owner['owner_type'] != 1) ? $owner['owner_city2'] : $owner['owner_city'],
                    "state"     => ($owner['owner_type'] != 1) ? $owner['owner_status2'] : $owner['owner_status'],
                    "postal_code"=> ($owner['owner_type'] != 1) ? $owner['owner_zip2'] : $owner['owner_zip'],
                ],
                "phone" => ($owner['owner_type'] != 1) ? $owner['owner_phone2'] : $owner['owner_phone'],
            ],
            "attester_name"     => $applicant['first_name'] . " " . $applicant['last_name'],
            "attestation_date"  =>date("Y-m-d" , $list['ctime']) ,
            "attestation_consent" => true
        ];
    }

    public function checkEdit()
    {
        $model = new UserCheck();
        if($this->request->isPost()) {
            $data = input('param.');
            if($data['check_status'] == 1){
                $data += ['sent_info' => $this->getCheckInfo($data['check_id'])];
            }
            $model = new UserCheck();
            $re = $model->updateCheckStatus($data + [
                                'manage_id' =>$this->manage_id]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }
        $id     = input('get.id');
        $list   = $model->find($id);
        View::assign('data', [
            'id'            => $id,
            'username'      => $list['username'],
            'check_status'  => $list['check_status'],
            'applicant'     => json_decode($list['applicant'] ,true),
            'business_one'  => json_decode($list['business_one'] ,true),
            'business_two'  => json_decode($list['business_two'] ,true),
            'owner'         => json_decode($list['owner'] ,true),
            'bus_img'       => explode(',' , $list['document_bus_img']),
            'pre_img'       => explode(',' , $list['document_pre_img'])
        ]);
        return View::fetch();
    }

    public function activeBusiness()
    {
        $data       = input('param.');
        $cdModel    = new UserCheck();
        $re         = $cdModel->activeBusiness($data + ['manage_id' =>$this->manage_id]);
        if($re){
            return $this->scs('Active success');
        }else{
            return $this->err('Active error');
        }
    }

    public function sentKyc()
    {
        $data       = input('param.');
        $cdModel    = new UserCheck();
        $re         = $cdModel->sentKyc($data + ['manage_id' =>$this->manage_id]);
        if($re){
            return $this->scs('Sent success');
        }else{
            return $this->err('Sent error');
        }
    }

    public function changeKyc()
    {
        $data       = input('param.');
        $cdModel    = new UserCheck();
        $re         = $cdModel->changeKyc($data + ['manage_id' =>$this->manage_id]);
        if($re){
            return $this->scs('Change success');
        }else{
            return $this->err('Change error');
        }
    }

    public function UserCardMax()
    {
        if($this->request->isAjax())
        {
            $userModel = new ManageCard();
            return $userModel->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function maxRemark()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $fund_id        = $data['max_id'];
            $remark         = $data['remark'];
            $fcModel = new ManageCard();
            $re = $fcModel->where(['id'=>$fund_id])->update(['remark'=>$remark]);

            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $id     = input('get.id');
        $fcModel = new ManageCard();
        $list = $fcModel->find($id);

        View::assign([
            'remark'    => $list['remark'],
            'max_id'    => $id,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function userTotal()
    {
        if($this->request->isAjax())
        {
            $user_list = Db::name('user')->field("FROM_UNIXTIME(ctime+8*60*60,'%Y%m%d') days,COUNT(id) user_num")
                ->where('id !=1')->group('days')->select()->toArray();
            $fund_list_c = Db::name('fund_check')->field("FROM_UNIXTIME(ctime+8*60*60,'%Y%m%d') days,sum(amount) fund_amount")
                ->where('user_id !=1 and check_status=1 and type=0')->group('days')->select()->toArray();
            $fund_list_d = Db::name('fund_check')->field("FROM_UNIXTIME(ctime+8*60*60,'%Y%m%d') days,sum(amount) fund_amount")
                ->where('user_id !=1 and check_status=1 and type=1')->group('days')->select()->toArray();
            $card_list = Db::name('cards')
                ->field("FROM_UNIXTIME(ctime+8*60*60,'%Y%m%d') days,
                                COUNT(id) card_num,
                                sum(open_amount) open_amount,
                                sum(server_amount) server_amount,
                                sum(refund_amount) refund_amount")
                ->where('user_id !=1')->group('days')->select()->toArray();
            $tran_list = Db::name('cards_trans')->field("DATE_FORMAT(ctime,'%Y%m%d') days,sum(amount_post) post_amount")
                ->where("user_id !=1 and tran_status='Posted'")->group('days')->select()->toArray();
            $tran_list2 = Db::name('cards_trans')->field("DATE_FORMAT(ctime,'%Y%m%d') days,sum(amount_post) credit_amount")
                ->where("user_id !=1 and tran_status='Credit' and bank_type!=3")->group('days')->select()->toArray();
            $tran_list3 = Db::name('cards_trans')->field("DATE_FORMAT(ctime,'%Y%m%d') days,sum(amount_post) credit_amount")
                ->where("user_id !=1 and tran_status='Credit' and bank_type =3")->group('days')->select()->toArray();
            $total_list = [];
            foreach ($user_list as $k=>$v){
                $total_list[$v['days']]['user_num'] = $v['user_num'];
            }
            foreach ($card_list as $k_card=>$v_card){
                $total_list[$v_card['days']]['card_num'] =$v_card['card_num'];
                $total_list[$v_card['days']]['open_amount'] =$v_card['open_amount'];
                $total_list[$v_card['days']]['server_amount'] =$v_card['server_amount'];
                $total_list[$v_card['days']]['refund_amount'] =$v_card['refund_amount'];
            }
            foreach ($fund_list_c as $k_fund=>$v_fund){
                $total_list[$v_fund['days']]['fund_amount_c'] =$v_fund['fund_amount'];
            }
            foreach ($fund_list_d as $k_fund_d=>$v_fund_d){
                $total_list[$v_fund_d['days']]['fund_amount_d'] =$v_fund_d['fund_amount'];
            }
            foreach ($tran_list as $k_tran=>$v_tran){
                $total_list[$v_tran['days']]['post_amount'] =$v_tran['post_amount'];
            }
            foreach ($tran_list2 as $k_tran2=>$v_tran2){
                $total_list[$v_tran2['days']]['credit_amount'] =$v_tran2['credit_amount'];
            }
            foreach ($tran_list3 as $k_tran3=>$v_tran3){
                $total_list[$v_tran3['days']]['credit_amount3'] = -$v_tran3['credit_amount'];
            }
            $new_list = [];
            $new_list1 = [];
            $weekArray = [
                '1' => '星期一',
                '2' => '星期二',
                '3' => '星期三',
                '4' => '星期四',
                '5' => '星期五',
                '6' => '星期六',
                '7' => '星期日',
            ];

            foreach($total_list as $k_total=>$v_total){
                $new_list1['time'] = $k_total;
                $timeN             = strtotime($k_total);
                $timeN             = date('N',$timeN);
                $timeN             = $weekArray[$timeN];
                $kk_total           = substr($k_total , 0,4) . '/' . substr($k_total , 4,2) . '/' . substr($k_total , 6,2);
                $new_list1['timeN'] = $kk_total . ' (' . $timeN . ')';
                $new_list1['user_num']  = $v_total['user_num'] ?? 0;
                $new_list1['card_num']  = $v_total['card_num'] ?? 0;
                $new_list1['open_amount'] = $v_total['open_amount'] ?? 0.00;
                $new_list1['server_amount'] = $v_total['server_amount'] ?? 0.00;
                $new_list1['refund_amount'] = $v_total['refund_amount'] ?? 0.00;
                $new_list1['fund_amount'] = ($v_total['fund_amount_c'] ?? 0) - ($v_total['fund_amount_d'] ?? 0);
                $new_list1['post_amount'] = $v_total['post_amount'] ?? 0.00;
                $new_list1['credit_amount'] = $v_total['credit_amount'] ?? 0.00;
                $new_list1['credit_amount3'] = $v_total['credit_amount3'] ?? 0.00;
                $new_list[] = $new_list1;
            }
            $bb = array_column($new_list , 'time');
            array_multisort($bb , SORT_DESC , $new_list);
            return [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $new_list,
                'count' => count($new_list),
            ];
        }
        return View::fetch();
    }

    public function userFundRate()
    {
        if($this->request->isAjax()) {
            try {
                $user_status_get = input('get.user_status','');
                $username        = trim(input('get.username',''));

                $fund_check = Db::name('fund_check')
                    ->field('sum(amount) fc_amount , user_id')
                    ->where(['check_status'=>1])->group('user_id')->select()->toArray();
                $fund_array =[];
                foreach ($fund_check as $k_fund => $v_fund) {
                    $fund_array[$v_fund['user_id']] = $v_fund['fc_amount'];
                }
                $user_list  = Db::name('user')
                    ->field('id,username,status')
                    ->select()->toArray();
                $name_array = [];
                $status_array=[];
                foreach ($user_list as $k_user => $v_user) {
                    $name_array[$v_user['id']] = $v_user['username'];
                    $status_array[$v_user['id']] = $v_user['status'];
                }
                $list_new = [];
                $list_old = [];
                $tran_check = Db::name('cards_trans')
                    ->field('sum(amount_auth) dec_amount , user_id')
                    ->where(['tran_status'=>'Declined'])->group('user_id')->select()->toArray();
                foreach ($tran_check as $k_tran => $v_tran) {
                    $user_id = $v_tran['user_id'];
                    $user_status = $status_array[$user_id];
                    if(isset($fund_array[$user_id])){
                        $fc_amount = $fund_array[$user_id];
                        $dec_amount = $v_tran['dec_amount'];
                        $amount_rate = 0;
                        if ($dec_amount != 0) {
                            $amount_rate = getSprintf(round($fc_amount / $dec_amount, 2));
                        }
                        if ($amount_rate <= 0.5 && $amount_rate > 0) {
                            $list_old['active_card'] = Db::name('cards')
                                ->where([
                                    'user_id'=>$user_id,
                                    'status' =>1
                                ])->count();
                            $list_old['user_id'] = $user_id;
                            $list_old['username'] = $name_array[$user_id];
                            $list_old['status'] = $user_status;
                            $list_old['fc_amount'] = $fc_amount;
                            $list_old['dec_amount'] = $dec_amount;
                            $list_old['amount_rate'] = $amount_rate;
                            $list_new[] = $list_old;
                        }
                    }
                }
                $bb = array_column($list_new , 'amount_rate');
                array_multisort($bb , SORT_DESC , SORT_NUMERIC, $list_new);

                $list_new_1 =[];
                if(!empty($user_status_get)){
                    foreach ($list_new as $k=>$v_new){
                        if($user_status_get == $v_new['status']){
                            $list_new_1[] = $v_new;
                        }
                    }
                }
                if(!empty($list_new_1)){
                    $list_new = $list_new_1;
                }
                $list_new_2 =[];
                if(!empty($username)){
                    foreach ($list_new as $k=>$v_new){
                        if($username == $v_new['username']){
                            $list_new_2[] = $v_new;
                        }
                    }
                }
                if(!empty($list_new_2)){
                    $list_new = $list_new_2;
                }
                return [
                    'code' => 0,
                    'msg' => lang('get info success'),
                    'data' => $list_new,
                    'count' => count($list_new),
                ];
            } catch (\Exception $e) {
                var_dump($e->getMessage());
            }
        }
        return View::fetch();
    }

    public function userIce()
    {
        $data = input('param.');
        $num  = UserModel::changeUserCardStatus($data , $this->manage_id);
        if($num){
            return $this->scs("{$num} 更新成功.");
        }else{
            return $this->err('更新失败.');
        }
    }

    public function userActive()
    {
        $data = input('param.');
        $num  = UserModel::changeUserStatus($data , $this->manage_id);
        if($num){
            return $this->scs("{$num} 名用户已激活.");
        }else{
            return $this->err('用户激活失败');
        }
    }

    public function allFund()
    {
        if($this->request->isAjax())
        {
            $userModel = new FundCheck();
            return $userModel->tableAllFund(input('param.'));
        }
        return View::fetch();
    }

    public function veriffCheck()
    {
        if($this->request->isAjax())
        {
            $userModel = new UserCheck();
            return $userModel->tableDataVeriff(input('param.'));
        }
        return View::fetch();
    }

    public function editVeriff()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $is_rep     = $data['is_rep'];
            $v_id       = $data['v_id'];
            $remark     = $data['remark'];
            $manage_id  = $this->manage_id;

            if($is_rep == 1){
                $re         = Db::name('user_veriff')->where(['id'=>$v_id])->delete();
            }else{
                $re         = Db::name('user_veriff')->where(['id'=>$v_id])
                    ->update([
                        'is_rep'=>'Sys Expired',
                        'remark'=>$remark
                    ]);
            }
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $v_id = input('get.v_id');

        $user_veriff_info = Db::name('user_veriff')->where(['id' => $v_id])->find();
        View::assign([
            'v_id'         => $v_id,
            'list'         => $user_veriff_info,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

}
